package net.jgrm.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.jgrm.common.model.Result;
import net.jgrm.common.util.ExcelUtils;
import net.jgrm.common.util.ResultUtils;
import net.jgrm.order.dto.CreateOrderRequest;
import net.jgrm.order.dto.OrderExportDTO;
import net.jgrm.order.dto.PaymentCallbackRequest;
import net.jgrm.order.dto.QueryOrderParams;
import net.jgrm.order.entity.Order;
import net.jgrm.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * 订单服务控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private IOrderService orderService;
//    @Autowired
//    private OrderThreadPoolConfig orderThreadPoolConfig;

    //    @Autowired
//    @Qualifier(value = "taskExecutor")
//    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    @Qualifier(value = "gracefulTaskExecutor")
    private ThreadPoolTaskExecutor gracefulTaskExecutor;

    /**
     * 使用Feign调用商品服务创建订单
     */
    @PostMapping("/create-with-feign")
    @SentinelResource(value = "api_createOrderWithFeign", blockHandler = "createOrderBlockHandler")
    public Result<Order> createOrderWithFeign(
            @RequestParam Long userId,
            @RequestParam Long productId,
            @RequestParam Integer quantity) {
        return ResultUtils.getSuccessResult(orderService.createOrderWithFeign(userId, productId, quantity));
    }

    /**
     * 使用Dubbo调用商品服务创建订单
     */
    @PostMapping("/create-with-dubbo")
    @SentinelResource(value = "api_createOrderWithDubbo", blockHandler = "createOrderBlockHandler")
    public Result<Order> createOrderWithDubbo(
            @RequestParam Long userId,
            @RequestParam Long productId,
            @RequestParam Integer quantity) {
        return ResultUtils.getSuccessResult(orderService.createOrderWithDubbo(userId, productId, quantity));
    }

    /**
     * 创建订单 - 包含收货人信息和库存检查
     */
    @PostMapping("/create")
    @SentinelResource(value = "api_createOrderWithReceiverInfo", blockHandler = "createOrderBlockHandler")
    public Result<Order> createOrder(@Valid @RequestBody CreateOrderRequest request) {
        try {
            Order order = orderService.createOrderWithReceiverInfo(request);
            return ResultUtils.getSuccessResult(order);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return ResultUtils.getErrorResult(e.getMessage());
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResultUtils.getErrorResult(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.getErrorResult();
        }
    }

    /**
     * 支付成功回调接口
     */
    @PostMapping("/payment/callback")
    public Result paymentCallback(@Valid @RequestBody PaymentCallbackRequest request) {
        try {
            boolean success = orderService.handlePaymentCallback(request);
            if (success) {
                return ResultUtils.getSuccessResult("支付回调处理成功");
            } else {
                return ResultUtils.getErrorResult("支付回调处理失败");
            }
        } catch (Exception e) {
            return ResultUtils.getErrorResult(e.getMessage());
        }
    }

    /**
     * 根据收货人姓名查询订单（支持加密数据查询）
     */
    @GetMapping("/search/by-receiver-name")
    public Result<List<Order>> searchByReceiverName(@RequestParam String receiverName) {
        try {
            if (receiverName == null || receiverName.trim().isEmpty()) {
                return ResultUtils.getErrorResult("收货人姓名不能为空");
            }
            List<Order> orders = orderService.findOrdersByReceiverName(receiverName.trim());
            return ResultUtils.getSuccessResult(orders);
        } catch (Exception e) {
            return ResultUtils.getErrorResult(e.getMessage());
        }
    }

    /**
     * 根据收货人手机号查询订单（支持加密数据查询）
     */
    @GetMapping("/search/by-receiver-phone")
    public Result<List<Order>> searchByReceiverPhone(@RequestParam String receiverPhone) {
        try {
            if (receiverPhone == null || receiverPhone.trim().isEmpty()) {
                return ResultUtils.getErrorResult("收货人手机号不能为空");
            }

            List<Order> orders;
            String phone = receiverPhone.trim();

            // 根据手机号长度选择不同的查询方式
            if (phone.length() == 11) {
                // 完整手机号，使用加密索引查询
                orders = orderService.findOrdersByReceiverPhone(phone);
            } else if (phone.length() == 4) {
                // 手机号后4位，使用后缀查询
                orders = orderService.findOrdersByReceiverPhoneSuffix(phone);
            } else if (phone.length() == 3) {
                // 手机号前3位，使用前缀查询
                orders = orderService.findOrdersByReceiverPhonePrefix(phone);
            } else {
                return ResultUtils.getErrorResult("手机号格式不正确，应为11位完整手机号、3位前缀或4位后缀");
            }

            return ResultUtils.getSuccessResult(orders);
        } catch (Exception e) {
            return ResultUtils.getErrorResult(e.getMessage());
        }
    }

    /**
     * 根据手机号前缀查询订单
     */
    @GetMapping("/search/by-receiver-phone-prefix")
    public Result<List<Order>> searchByReceiverPhonePrefix(@RequestParam String phonePrefix) {
        try {
            if (phonePrefix == null || phonePrefix.trim().isEmpty()) {
                return ResultUtils.getErrorResult("手机号前缀不能为空");
            }

            if (phonePrefix.trim().length() != 3) {
                return ResultUtils.getErrorResult("手机号前缀应为3位数字");
            }

            List<Order> orders = orderService.findOrdersByReceiverPhonePrefix(phonePrefix.trim());
            return ResultUtils.getSuccessResult(orders);
        } catch (Exception e) {
            return ResultUtils.getErrorResult(e.getMessage());
        }
    }

    /**
     * 根据手机号后缀查询订单
     */
    @GetMapping("/search/by-receiver-phone-suffix")
    public Result<List<Order>> searchByReceiverPhoneSuffix(@RequestParam String phoneSuffix) {
        try {
            if (phoneSuffix == null || phoneSuffix.trim().isEmpty()) {
                return ResultUtils.getErrorResult("手机号后缀不能为空");
            }

            if (phoneSuffix.trim().length() != 4) {
                return ResultUtils.getErrorResult("手机号后缀应为4位数字");
            }

            List<Order> orders = orderService.findOrdersByReceiverPhoneSuffix(phoneSuffix.trim());
            return ResultUtils.getSuccessResult(orders);
        } catch (Exception e) {
            return ResultUtils.getErrorResult(e.getMessage());
        }
    }

    /**
     * 分页查询订单列表
     * 支持多种条件组合查询
     *
     * @return 分页结果
     */
    @PostMapping("/page")
    public Result findOrdersByQueryOrderParams(@RequestBody QueryOrderParams queryParams) {
        // 构建分页对象
        Page<Order> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());
        // 调用服务层方法进行分页查询
        Page<Order> resultPage = orderService.findOrdersByQueryOrderParams(page, queryParams);
        // 封装返回结果
        return ResultUtils.getSuccessResult(resultPage);
    }

    // 接口限流/熔断处理
    public Result<Order> createOrderBlockHandler(Long userId, Long productId, Integer quantity, BlockException e) {
        e.printStackTrace();
        Order errorOrder = new Order();
        errorOrder.setOrderNo("API_BLOCK_" + System.currentTimeMillis());
        // 标识为接口限流订单
        errorOrder.setStatus(-3);
        return ResultUtils.getErrorResult("接口限流/熔断", errorOrder);
    }

//    @GetMapping("/threadpool/config")
//    public String getThreadPoolConfig() {
//
//
//        // 查询taskExecutor线程池的配置信息
//        int corePoolSize = taskExecutor.getCorePoolSize();
//        int maxPoolSize = taskExecutor.getMaxPoolSize();
//        int queueCapacity = taskExecutor.getQueueCapacity();
//
//        System.out.println(String.format("池内的配置大小信息： CorePoolSize: %d, MaxPoolSize: %d, QueueCapacity: %d",
//                corePoolSize,
//                maxPoolSize,
//                queueCapacity));
//
//        return String.format("配置信息：CorePoolSize: %d, MaxPoolSize: %d, QueueCapacity: %d",
//                orderThreadPoolConfig.getCorePoolSize(),
//                orderThreadPoolConfig.getMaxPoolSize(),
//                orderThreadPoolConfig.getQueueCapacity());
//    }

    @GetMapping("/threadpool/config/v2")
    public String getThreadPoolConfigV2() {
        // 查询taskExecutor线程池的配置信息
        int corePoolSize = gracefulTaskExecutor.getCorePoolSize();
        int maxPoolSize = gracefulTaskExecutor.getMaxPoolSize();
        int queueCapacity = gracefulTaskExecutor.getQueueCapacity();

        // 查询当前线程池的活跃线程数
        int activeCount = gracefulTaskExecutor.getActiveCount();
        int queueSize = gracefulTaskExecutor.getThreadPoolExecutor().getQueue().size();

        System.out.println("执行任务前 - 当前活跃线程数: " + activeCount + ", 队列大小: " + queueSize);

        // 插入100个需要执行3秒的任务来测试迁移效果
        for (int i = 0; i < 100; i++) {
            final int taskId = i;
            gracefulTaskExecutor.execute(() -> {
                try {
                    System.out.println("任务 " + taskId + " 开始执行，线程: " + Thread.currentThread().getName());
                    // 模拟耗时任务，等待3秒
                    Thread.sleep(3000);
                    System.out.println("任务 " + taskId + " 执行完成，线程: " + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    System.out.println("任务 " + taskId + " 被中断，线程: " + Thread.currentThread().getName());
                    Thread.currentThread().interrupt();
                }
            });
        }

        // 等待一小段时间让任务开始执行
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 再次检查线程池状态
        activeCount = gracefulTaskExecutor.getActiveCount();
        queueSize = gracefulTaskExecutor.getThreadPoolExecutor().getQueue().size();
        System.out.println("提交任务后 - 当前活跃线程数: " + activeCount + ", 队列大小: " + queueSize);

        String result = String.format("池内的配置大小信息： CorePoolSize: %d, MaxPoolSize: %d, QueueCapacity: %d<br/>" +
                        "当前活跃线程数: %d, 队列任务数: %d<br/>" +
                        "已提交100个测试任务，每个任务执行3秒",
                corePoolSize, maxPoolSize, queueCapacity, activeCount, queueSize);

        return result;
    }
    
    /**
     * 导出订单数据到Excel文件
     */
    @PostMapping("/export")
    public void exportOrders(@RequestBody QueryOrderParams queryParams, HttpServletResponse response) {
        log.info("开始导出订单数据，参数: {}", queryParams);
        try {
            // 查询订单数据
            List<OrderExportDTO> exportData = orderService.exportOrders(queryParams);
            
            // 使用通用Excel工具类导出数据
            ExcelUtils.exportExcel(response, "订单数据", exportData, OrderExportDTO.class, "订单列表");
        } catch (Exception e) {
            log.error("导出订单数据失败: {}", e.getMessage(), e);
            // ExcelUtils内部已处理异常响应，这里只需记录日志
        }
    }
}
